package cn.crawler.framework.util;

import org.nutz.log.Log;
import org.nutz.log.Logs;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ScriptUtil {

    private static final Log log = Logs.get();

    public static boolean execute(String script) {
        // 获取系统名
        String osName = System.getProperty("os.name");
        // Windows
        if (osName.startsWith("Windows")) {
            return cmd(script);
        }
        // 苹果 Mac OS
        else if (osName.startsWith("Mac")) {
        }
        // 其他系统：即 Linux/Unix
        else {
            log.info("current process running shell '" + script + "';");
            return shell(script);
        }
        return false;
    }

    private static boolean shell(String script) {
        try {
            ProcessBuilder builder =
//                    new ProcessBuilder(script);
                    new ProcessBuilder("/bin/sh", "-c",script);
            Process process = builder.start();
            StringBuffer sb = new StringBuffer();
            String line = null;
            BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
            while ((line = br.readLine()) != null) {
                sb.append(line);
                sb.append(" ");
            }
            log.info(sb);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    private static boolean cmd(String script) {
        Process p = null;
        try {
            p = Runtime.getRuntime().exec(script);
        } catch (IOException e) {
            log.error(e);
        }
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
            String readLine = br.readLine();
            StringBuilder builder = new StringBuilder();
            while (readLine != null) {
                readLine = br.readLine();
                builder.append(readLine);
            }
            p.waitFor();
            int i = p.exitValue();
            if (i == 0) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            log.error(e);
        }  finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    log.error(e);
                }
            }
        }
        return true;
    }

}
